// pages/newclasscirlevideo/newclasscirlevedio.js
const app = getApp()
const qiniuUploader = require("../../utils/qiniuUploader");
var utils = require('../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    content: "", // 文本的内容
    "placeholder": "记录宝贝的每个成长瞬间",
    "maxlength": 100, // 最大输入长度，设置为 -1 的时候不限制最大长度
    "focus": true,
    "auto-height": true, // 是否自动增高，设置auto-height时，style.height不生效
    "adjust-position": true, // 键盘弹起时，是否自动上推页面
    "addbtn": "../../images/icon_addpic_unfocused.png",
    "photoList": [],
    photourl: [],
    qiniuToken: "",
    fabuflag:false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getQiniuToken();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //失去焦点时获取里面评论内容
  bindTextAreaBlur: function (e) {
    console.log(e.detail.value)
    this.setData({
      content: e.detail.value,
    })
  },

  //获取用户输入内容
  contentInput: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  fabubtnclick: function (e) {

    if(this.data.fabuflag==true){
      return
    }


    if (this.data.photoList.length == 0 && this.data.content.length == 0) {
      wx.showToast({
        title: "请添加发布内容",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      return
    }

    this.setData({
      photourl: []
    })

    this.setData({
      fabuflag:true
    })

    if (this.data.photoList.length > 0) {
      this.sendImge(this.data.photoList[0]);
    } else {

      wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
      wx.showLoading({ //显示 loading 提示框
        title: "正在发布...",
      })
      this.postData()
    }
  },

  addbtnclick: function (e) {
    var that = this;
    var photoList = this.data.photoList;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        var tempFilePath = res.tempFilePath; // 返回选定照片的本地路径列表 
        that.setData({
          photoList: photoList.concat(tempFilePath)
        })
        console.log(res.tempFilePath)
      }
    })
    console.log(this.data.photoList)
  },

  deletebtnclick: function (e) {
    var index = e.currentTarget.dataset.index;
    console.log("index" + index)
    var photoList = this.data.photoList;
    photoList.splice(index, 1)
    this.setData({
      photoList: photoList,
    })

  },


  getQiniuToken: function (e) {
    var that = this;
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan
    }
    wx.request({
      url: app.globalData.serverQiNiuUrl,
      data: {
        "data": JSON.stringify(data)
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          that.setData({
            qiniuToken: res.data.data.token
          })
        } else {

        }
      },
      fail: function (res) {

      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },



  postData: function (e) {
    var that = this;
    var message = [{
      "sType": 2,
      "attachmentID": 0,
      "attachmentUrl": this.data.photourl[0]
    }]
    var data = {
      "userid": app.globalData.userId,
      "schoolid": app.globalData.schoolId,
      "content": that.data.content,
      "data": message,
      "appType": app.globalData.appType,
      "appKey": app.globalData.appKey,
      "timeSpan": app.globalData.timespan,
      "mobileSerialnumber": ""
    }
    wx.request({
      url: app.globalData.serverUrl,
      data: {
        "data": JSON.stringify(data),
        'act': "send_show_class"
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success: function (res) {
        console.log(res);
        if (res.data.status == 0) {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布成功",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          wx.navigateBack({
            url: '../classcirle/classcirleindex'
          })
        } else {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "发布失败",
            icon: 'none',
            duration: 1000,
            mask: true
          })
          that.setData({
            fabuflag:false
          })
        }
      },
      fail: function (res) {
        wx.hideNavigationBarLoading()
        wx.hideLoading()
        wx.showToast({
          title: "发布失败",
          icon: 'none',
          duration: 1000,
          mask: true
        })
        that.setData({
          fabuflag:false
        })
      },
      complete: function (res) {
        console.log('submit complete');
      }
    })
  },


  sendImge: function (filepath) {

    wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
    wx.showLoading({ //显示 loading 提示框
      title: "正在发布...",
    })

    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;

    var _this = this
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
    qiniuUploader.upload(filepath, res => {
      console.log(res)
      var url = res.imageURL
      var pathList = _this.data.photourl;
      pathList.push(url)
      _this.setData({
        //注意这中间有个"/"在这上面耽误了半个小时
        photourl: pathList
      })
      _this.postData()
    }, (error) => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
      wx.showToast({
        title: "发布失败",
        icon: 'none',
        duration: 1000,
        mask: true
      })
      _this.setData({
        fabuflag:false
      })
    }, {
      key: "jygy/" + "photo/" + app.globalData.schoolId + "/" + app.globalData.classid + "/" + timestamp + "/" + utils.formatDate(new Date()) + utils.wxuuid() + ".mp4",
      region: 'NCN',
      uptoken: _this.data.qiniuToken,
      uploadURL: 'https://up-z1.qbox.me',
      domain: app.globalData.qiniurUrl,
    })
  }

})